/* eslint-disable no-param-reassign */
import React, { Component } from 'react';
import fetch from 'dva/fetch';
import { Tree } from 'antd';
import * as config from '../../../utils/config';
import styles from './Tree.css';
import * as commonFunc from '../commonFunc';

const { TreeNode } = Tree;

class TreeComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      componentName: props.componentName,
      treeData: [],
      selectedKeys: [], /* 选中树 */
      componentVisible: false, /* 树是否显示 */
    };
  }
  componentWillMount() {
    const { gdsconfigformslave } = this.props.config;
    const treeData = commonFunc.getTreeConfigData(gdsconfigformslave);
    const componentVisible = treeData.length > 0;
    this.setState({ treeData, componentVisible });
  }

  componentWillReceiveProps(nextProps) {
    const { dataList } = nextProps.content;
    const {
      sDataListTabId, componentName, returnType, loading,
    } = dataList;
    if (nextProps.sTabId === sDataListTabId && this.state.componentName === componentName) {
      if (loading) return;
      if (returnType === 'isSearch') {
        this.setState({ selectedKeys: [] });
      }
    }
  }

  shouldComponentUpdate(nextProps, nextState) {
    const { dataList } = nextProps.content;
    const { sDataListTabId, componentName } = dataList;
    if (nextState.treeData !== this.state.treeData) return true;
    if (nextState.selectedKeys !== this.state.selectedKeys) return true;
    return nextProps.sTabId === sDataListTabId && nextState.componentName === componentName;
  }

  onLoadData = (treeNode) => {
    return new Promise((resolve) => {
      if (treeNode.props.children) {
        resolve();
        return;
      }
      setTimeout(() => {
        const { token } = this.props.app;
        const {
          sControlId, bTree, sName, isLeaf,
        } = treeNode.props.dataRef;
        /* sId为点击的节点Id, sModelsId为窗体Id, sControlId为列表Id */
        const sId = treeNode.props.dataRef.sId === sControlId ? '' : treeNode.props.dataRef.sId;
        if (!isLeaf) {
          const urls = `${config.server_host}business/getbFilterData/${sControlId}?sModelsId=${this.props.formId}&sDataParentId=${sId}`;
          const options = {
            method: 'GET',
            headers: {
              'Content-Type': 'application/json',
              authorization: token,
            },
          };
          fetch(urls, options).then(response => response.json()).then((data) => {
            const children = []; /* 子节点 */
            if (data.code === 1) {
              const { dataList } = data.dataset.rows[0];
              let index = 1;
              for (const child of dataList) {
                const isLeafNode = !(child.sChildren !== undefined && child.sChildren !== '' && bTree);
                index += 1;
                const num = new Date().getTime() + index;
                children.push({
                  showName: child.showName,
                  key: `${num}`,
                  isLeaf: isLeafNode,
                  bTree,
                  sId: child.sId, /* 数据Id */
                  sControlId,
                  sName,
                  bFilterValue: child.bFilterValue, /* 查询的值 */
                });
              }
              treeNode.props.dataRef.children = children;
              this.setState({
                treeData: [...this.state.treeData],
              });
            }
          });
        }
        resolve();
      }, 1000);
    });
  }

  onSelect = (selectedKeys, info) => {
    this.setState({ selectedKeys });
    const { bFilterValue, sName } =
      info.node.props.dataRef;
    const { filterCondition } = this.props;
    if (filterCondition !== undefined && Object.keys(filterCondition).length > 0) {
      filterCondition.forEach((obj, i) => {
        if (obj.bFilterCondition === 'inTree') {
          delete filterCondition.splice(i, 1);
        }
      });
    }
    const bFilter = [...filterCondition];
    if (bFilterValue !== undefined) {
      const treeBfilter = {
        bFilterName: sName,
        bFilterCondition: 'inTree',
        bFilterValue,
      };
      bFilter.push(treeBfilter);
    }
    this.props.onSaveFilter(bFilter);
  }


  renderTreeNodes = (data) => {
    return data.map((item) => {
      if (item.children) {
        return (
          <TreeNode
            title={item.showName}
            key={item.key}
            dataRef={item}
            isLeaf={item.isLeaf}
            className={styles.treeNode}
          >
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return (<TreeNode
        title={item.showName}
        key={item.key}
        dataRef={item}
        isLeaf={item.isLeaf}
        className={styles.treeNode}
      />);
    });
  }

  render() {
    const { componentVisible } = this.state;
    return (
      <div>
        { componentVisible ?
          <Tree
            showLine
            onSelect={this.onSelect}
            loadData={this.onLoadData}
            className={styles.tree}
            selectedKeys={this.state.selectedKeys}
          >
            {this.renderTreeNodes(this.state.treeData)}
          </Tree>
          : ''
        }
      </div>
    );
  }
}

export default TreeComponent;
